//
const { getByCode } = require('../../model/owner')
const { CodeNotExistErr } = require('../../response/code')
const { createRedisClient } = require('../../util/redis')

const { CODE_PREFIX } = require('../../consts/system')

// 项目code转id
const code2Id = async (ctx, next) => {
  try {
    const owner_id = await getCode2Id(ctx)
    if (!owner_id) {
      return ctx.app.emit('error', CodeNotExistErr, ctx)
    }
    ctx.state.owner_id = +owner_id
    await next()
  } catch (e) {
  } finally {
    ctx.state.owner_id = null
  }
}

const getCode2Id = async (ctx) => {
  const header = ctx.request.header
  // 取得token信息
  const code = header['code'] ? header['code'] : ''
  // console.log(header, '<<< code')
  if (!code || code === '') {
    ctx.app.emit('error', CodeNotExistErr, ctx)
    return null
  }

  const conn = createRedisClient()
  await conn.connect()
  //
  let owner_id = await conn.get(`${CODE_PREFIX}:${code}`)
  // 判断 code是否存在
  if (!owner_id) {
    // 查找数据,如果没有找到则返回错误
    const owner = await getByCode(code, {})
    if (!owner) return null

    owner_id = owner.id
    // 保存到redis
    await conn.set(`${CODE_PREFIX}:${code}`, owner_id)
    // 保存并进入下一步
  }
  await conn.close()
  return owner_id
}

module.exports = {
  code2Id,
}
